package com.biubiu.firefly.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.biubiu.firefly.R
import com.biubiu.firefly.databinding.FragmentSettingsBinding
import com.biubiu.firefly.utils.CircleCrop
import com.biubiu.firefly.wallpaper.box.BoxWallpaperService
import com.biubiu.firefly.wallpaper.box.ImageUtil
import com.biubiu.firefly.wallpaper.box.PictureAdapter
import com.biubiu.firefly.wallpaper.box.WorldFeatures
import com.esafirm.imagepicker.features.ImagePickerConfig
import com.esafirm.imagepicker.features.ImagePickerLauncher
import com.esafirm.imagepicker.features.ImagePickerMode
import com.esafirm.imagepicker.features.ImagePickerSavePath
import com.esafirm.imagepicker.features.ReturnMode
import com.esafirm.imagepicker.features.registerImagePicker
import com.esafirm.imagepicker.model.Image
import com.yanzhenjie.durban.Controller
import com.yanzhenjie.durban.Durban
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File


class BoxSettingsActivity : AppCompatActivity(){
    private lateinit var currentFragment: SettingsFragment

    companion object{
        private const val CROP_CODE = 1001
        private val REQUEST_CODE: Int = 1

        private const val IMAGE_WIDTH: Int = 250
        private const val IMAGE_HEIGHT: Int = 250
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == REQUEST_CODE){
            //检测权限是否全被授权
            if(grantResults.isNotEmpty()){
                for (grantResult in grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        //权限未被授权
                        Toast.makeText(this,"权限未被授权",Toast.LENGTH_SHORT).show()
                        return
                    }
                }
                //权限已被授权
                currentFragment.openThirdAlbum()
            }

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        if (savedInstanceState == null) {
            currentFragment = SettingsFragment()
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings, currentFragment)
                .commit()
        }
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == CROP_CODE) {
                val result = Durban.parseResult(data)
                if (result != null && result.size > 0) {
                    Log.v("liaoyucheng", result.toString())

                    val resultBitmap = arrayListOf<Bitmap>()
                    result.forEachIndexed { index, path ->
                        //处理返回的图片,转bitmap
                        val bitmap = BitmapFactory.decodeFile(path)

                        //圆形裁剪
                        val cropBitmap = CircleCrop.circleCrop(bitmap)

                        resultBitmap.add(cropBitmap)
                        //更新图片
                        currentFragment.updateImage(index, cropBitmap)
                    }
                    currentFragment.notifyDataSetChanged()
                }
            }
        }
    }

    class SettingsFragment : Fragment(), SeekBar.OnSeekBarChangeListener, OnClickListener  {
        private val mWorldFeatures: WorldFeatures = WorldFeatures.getWorldFeatures()
        private val pics = intArrayOf(
            R.drawable.bubble0, R.drawable.bubble1, R.drawable.bubble2, R.drawable.bubble3,
            R.drawable.bubble4, R.drawable.bubble5, R.drawable.bubble6, R.drawable.bubble7
        )
        private lateinit var dataBinding: FragmentSettingsBinding
        private val mHandler = Handler(Looper.myLooper()!!)
        private var launcher: ImagePickerLauncher? = null
        private var config: ImagePickerConfig? = null
        private val images = mutableListOf<Image>()
        private var currentPosition = 0
        private var isMultiple: Boolean = true

        private val mPictureAdapter by lazy {
            PictureAdapter()
        }

        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            dataBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.fragment_settings, container, false)
            initView()
            return dataBinding.root
        }

        private fun initView() {
            initImagePicker()
            dataBinding.apply {
                click = this@SettingsFragment
                seekBar1.setOnSeekBarChangeListener(this@SettingsFragment)
                seekBar2.setOnSeekBarChangeListener(this@SettingsFragment)
                seekBar3.setOnSeekBarChangeListener(this@SettingsFragment)
                seekBar4.setOnSeekBarChangeListener(this@SettingsFragment)
                seekBar1.progress = mWorldFeatures.getGravity()
                seekBar2.progress = ((mWorldFeatures.getRadius() - 75) / 50 * 100).toInt()
                seekBar3.progress = (10 * mWorldFeatures.getFriction()).toInt()
                seekBar4.progress = (10 * mWorldFeatures.getRestitution()).toInt()

                swRadius.setOnCheckedChangeListener { _, isChecked ->
                    tvTitle2.alpha = if(isChecked) 0.5f else 1f
                    seekBar2.alpha = if(isChecked) 0.5f else 1f
                    seekBar2.isEnabled = !isChecked

                    mWorldFeatures.isRandomRadius = isChecked
                }
                swRadius.isChecked = mWorldFeatures.isRandomRadius

                initAdapter()
                initListener()
            }
        }

        private fun initAdapter() {
            dataBinding.rvPicture.apply {
                layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
                adapter = mPictureAdapter
            }

            GlobalScope.launch {
                withContext(Dispatchers.IO) {
                    //获取图片资源
                    val bitmapList = arrayListOf<Bitmap>()
                    pics.forEach {
                        //精确缩放到指定大小
                        val thumbImg = Bitmap.createScaledBitmap(
                            BitmapFactory.decodeResource(resources, it),
                            IMAGE_WIDTH, IMAGE_HEIGHT, true
                        )
                        bitmapList.add(thumbImg)
                    }
                    Log.v("liaoyucheng", bitmapList.size.toString())
                    mHandler.post {

                        mPictureAdapter.setData(bitmapList)
                    }

                }
            }
        }

        private fun initListener() {
            mPictureAdapter.onItemClickListener = object : PictureAdapter.OnItemClickListener {
                override fun onItemClick(position: Int) {
                    currentPosition = position
                    isMultiple = false
                    openAlbum()
                }
            }
        }

        private fun initImagePicker() {
            launcher = registerImagePicker { result: List<Image> ->
                //相册反馈
                images.clear()
                images.addAll(result)

                val paths = arrayListOf<String>()
                result.forEach { image ->
                    val path = image.path
                    if(path.isEmpty() || !File(path).exists()){
                        Toast.makeText( activity, "文件不存在", Toast.LENGTH_SHORT).show()
                        return@forEach
                    }

                    paths.add(image.path)
                }

                Log.d("liaoyucheng", "相册选择的图片路径列表: $paths")

                //创建裁剪后图片的保存目录
                val file = File(requireActivity().cacheDir, "image_crop")
                if(!file.exists()){
                    file.mkdirs()
                }
                val destPath = file.absolutePath
                Log.d("liaoyucheng", "裁剪后图片的保存目录：$destPath")
                mHandler.post {
                    Durban.with(requireActivity())
                        .title("裁剪")
                        .statusBarColor(Color.parseColor("#393939"))
                        .toolBarColor(Color.parseColor("#393939"))
                        .inputImagePaths(paths)
                        .outputDirectory(destPath)
                        .maxWidthHeight(IMAGE_WIDTH, IMAGE_HEIGHT)
                        .aspectRatio(1f, 1f)
                        .compressFormat(Durban.COMPRESS_JPEG)
                        .compressQuality(90)
                        .gesture(Durban.GESTURE_SCALE)
                        .controller(
                            Controller.newBuilder()
                                .enable(false) // 是否开启控制面板。
                                .scale(true) // 是否有缩放按钮。
                                .scaleTitle(true) // 缩放控制按钮上面的标题。
                                .build()
                        )
                        .requestCode(CROP_CODE)
                        .start()
                }

            }
            //相册配置
            config = ImagePickerConfig {
                mode = ImagePickerMode.MULTIPLE // default is multi image mode
                language = "zh" // Set image picker language
                theme = R.style.dialog_style

                // set whether pick action or camera action should return immediate result or not. Only works in single mode for image picker
                returnMode = ReturnMode.NONE //ReturnMode.ALL else ReturnMode.NONE

                isFolderMode = true // set folder mode (false by default)
                //isIncludeVideo = true // include video (false by default)
                //isOnlyVideo = true // include video (false by default)
                arrowColor = Color.RED // set toolbar arrow up color
                folderTitle = "相册" // folder selection title
                imageTitle = "Tap to select" // image selection title
                doneButtonText = "确定" // done button text
                limit = pics.size // max images can be selected (99 by default)
                isShowCamera = false // show camera or not (true by default)
                savePath = ImagePickerSavePath("Camera") // captured image directory name ("Camera" folder by default)
                savePath =
                    ImagePickerSavePath(Environment.getExternalStorageDirectory().path, isRelative = false) // can be a full path

                //excludedImages = images.toFiles() // don't show anything on this selected images
                //selectedImages = images  // original selected images, used in multi mode
            }
        }

        //打开相册选择图片
        private fun openAlbum() {
            //创建一个数组，用于存储权限
            val permissions = arrayListOf<String>()
            // 检查权限
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )!= PackageManager.PERMISSION_GRANTED
            ) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )!= PackageManager.PERMISSION_GRANTED
            ) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }

            if(permissions.size > 0){
                // 申请权限
                ActivityCompat.requestPermissions(
                    requireActivity(),
                    permissions.toTypedArray(),
                    REQUEST_CODE
                )
            }else{
                //打开相册
                openThirdAlbum()
            }
        }

        /**
         * 开启相册
         */
        fun openThirdAlbum() {
            //打开相册
            config?.let {
                it.limit = if(isMultiple) pics.size else 1
                launcher?.launch(it)
            }
            //launcher.launch(CameraOnlyConfig())
        }

        fun updateImage(index: Int, bitmap: Bitmap){
            val position = if(isMultiple){
                index
            }else{
                currentPosition
            }
            //精确缩放到指定大小
            val bgImage = Bitmap.createScaledBitmap(
                BitmapFactory.decodeResource(resources, pics[position]),
                IMAGE_WIDTH + 10 , IMAGE_HEIGHT + 10 , true
            )
            //将图片叠加
            val overBitmap = ImageUtil.drawOverlapBitmap(bgImage, bitmap)
            mPictureAdapter.updateData(position, overBitmap)
        }

        @SuppressLint("NotifyDataSetChanged")
        fun notifyDataSetChanged(){
            mPictureAdapter.notifyDataSetChanged()
        }

        override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
            when(seekBar){
                dataBinding.seekBar1 ->{

                    dataBinding.tvTitle1.text = String.format(getString(R.string.gravity), progress)
                    mWorldFeatures.setGravity(progress)
                }
                dataBinding.seekBar2 ->{

                    dataBinding.tvTitle2.text = String.format(getString(R.string.radius), progress, "%")
                    mWorldFeatures.setRadius(progress * 50 / 100f + 75)
                }
                dataBinding.seekBar3 ->{

                    val friction = progress.toFloat()/dataBinding.seekBar3.max.toFloat()
                    dataBinding.tvTitle3.text = String.format(getString(R.string.frictional_force), friction)
                    mWorldFeatures.setFriction(friction)
                }
                dataBinding.seekBar4 ->{

                    val restitution = progress.toFloat()/dataBinding.seekBar4.max.toFloat()
                    dataBinding.tvTitle4.text = String.format(getString(R.string.elasticity), restitution)
                    mWorldFeatures.setRestitution(restitution)
                }
            }
        }

        override fun onStartTrackingTouch(seekBar: SeekBar?) {
        }

        override fun onStopTrackingTouch(seekBar: SeekBar?) {
        }

        override fun onClick(v: View?) {
            when (v){
                dataBinding.btnBack, dataBinding.btnCancel -> activity?.finish()
                dataBinding.btnSure -> {
                    mWorldFeatures.setStickers(mPictureAdapter.getData())
                    //跳转预览页
                    val intent = Intent("android.service.wallpaper.CHANGE_LIVE_WALLPAPER")
                    intent.putExtra(
                        "android.service.wallpaper.extra.LIVE_WALLPAPER_COMPONENT",
                        ComponentName(requireActivity(), BoxWallpaperService::class.java)
                    )
                    requireActivity().startActivity(intent)
                    activity?.finish()
                }
                dataBinding.btnMultiple -> {
                    isMultiple = true
                    openAlbum()
                }
            }
        }
    }
}